package com.mate.cloud;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;


/**
 * @description:    RocketMQ SDK同步发送消息测试
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/7/2 18:53
 * @updateUser:     MI
 * @updateTime:     2025/7/2 18:53
 * @updateRemark:   修改内容
 * @version:        1.0
 */
public class RocketMqSyncProducer {


    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
        // 实例化生产者组名称
        DefaultMQProducer producer = new DefaultMQProducer("order_sync_group");
        // 指定name server地址
        producer.setNamesrvAddr("192.168.110.17:9876");
        // 启动生产者实例
        producer.start();
        for (int i = 0; i < 3; i++) {
            // 创建消息实例，并指定主题、消息标签、消息内容
            Message msg = new Message("order_sync_topic" /* Topic */,"TagA" /* Tag */,
                    ("订单 -- " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            // 发送消息至RocketMQ服务端
            String orderMsg = new String(msg.getBody(), StandardCharsets.UTF_8);
            System.out.println("发送订单消息：" + orderMsg);
            SendResult sendResult = producer.send(msg);
            System.out.printf("消息发送结果：msgId=%s, queueId=%d%n", sendResult.getMsgId(), sendResult.getMessageQueue().getQueueId());
        }
        // 关闭不再使用的生产者实例
        producer.shutdown();
    }
}
